package main

import (
	"sync"
	"encoding/json"
	"fmt"
	"time"
)

type BigOneMarketShort struct {
	Symbol string
}

type BigOneMarketsShort struct {
	Data []BigOneMarketShort
}

type BigOneMarket struct{
	Type string
	Symbol string
	Base string
	Quote string
	Base_min string // 不知道为什么不能用float64
	Base_max string
	Quote_increment string
	Total_min string
	Base_name string
	Quote_name string
	Ticker struct{
		Price string
		Low string
		High string
		Open string
		Close string
		Volume string
	}
}

type BigOneMarkets struct{
	Data []BigOneMarket
}

type BigOneMarketSingle struct{
	Data BigOneMarket
}

func bigOneMarketsToRedis(wg *sync.WaitGroup) error{
	defer wg.Done()

	t := time.Now()

	// fmt.Printf("bigOneMarketsToRedis begin\n")

	val, err := client.Get("BigOneMarketList").Result()
	if err != nil{
		fmt.Printf("bigOneMarketsToRedis() Error: %s\n", err)
		return err
	}

	var marketlist BigOneMarketsShort
	err = json.Unmarshal([]byte(val), &marketlist)
	if err != nil{
		fmt.Printf("bigOneMarketsToRedis() Error: %s\n", err)
		return err
	}

	var local_wg sync.WaitGroup

	for v := range marketlist.Data {
		local_wg.Add(1)
		go BigOneMarketToRedis(marketlist.Data[v].Symbol, &local_wg)
	}

	local_wg.Wait()
	
	fmt.Printf("bigOneMarketsToRedis Duration: %s\n", time.Now().Sub(t))
	return nil
}

func BigOneMarketToRedis(symbol string, wg *sync.WaitGroup) error{
	defer wg.Done()

	url := "https://api.big.one/markets/" + symbol

	body := httpGet(url)

	var market BigOneMarketSingle

	err := json.Unmarshal(body, &market)
	if err != nil {
		fmt.Printf("BigOneMarketToRedis() Error: %s\n", err)
		return err
	}

	key := "BigOne_" + market.Data.Quote + "_" + market.Data.Base + "_latest"

	sdata, err := json.Marshal(market.Data)
	if err != nil {
		fmt.Printf("BigOneMarketToRedis() Error: %s\n", err)
		return err
	}

	err = client.Set(key, sdata, 0).Err()
	if err != nil {
		fmt.Printf("Key: %s Error: %s\n", key, err)
		return err
	}

	return nil
}

func PullBigOneMarkets(wg *sync.WaitGroup){
	defer wg.Done()

	url := "https://api.big.one/markets"

	body := httpGet(url)

	var marketsShort BigOneMarketsShort

	err := json.Unmarshal(body, &marketsShort)
	if err != nil{
		fmt.Printf("PullBigOneMarkets() Error: %s\n", err)
	}

	value, err := json.Marshal(marketsShort)

	key := "BigOneMarketList"

	err = client.Set(key, value, 0).Err()
	if err != nil {
		fmt.Printf("Key: %s Error: %s\n", key, err)
	}
}